package com.ccnu.sm.controller;

import com.ccnu.sm.domain.User;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping(value="/user")
@SessionAttributes("user")
public class UserController {
	private static final Log logger = LogFactory.getLog(UserController.class);
	private static List<User> userList;
	public UserController() {
		super();
		userList = new ArrayList<User>();
	}
	
//	@ModelAttribute("username")
//	public String mapping(@RequestParam(value="username") String username) {
//		return username;
//	}

	@RequestMapping(value="/PathVariable/{userId}", method=RequestMethod.GET)
	public String pathVariableTest(
			@PathVariable Integer userId,
			@CookieValue(value="JSESSIONID", defaultValue="") String sessionId
			) {
		logger.info("register GET 正在被调用 userId=[" + userId + "] session=[" + sessionId+"]");
		return "registerForm";
	}
	
	@RequestMapping(value="/", method=RequestMethod.GET)
	public String userRoot() {
		logger.info("UserController.userRoot GET 正在被调用");
		return "registerForm";
	}
	
	@RequestMapping(value="/register", method=RequestMethod.GET)
	public String registerForm() {
		logger.info("register GET 正在被调用");
		return "registerForm";
	}
	
	@RequestMapping(value="/register", method=RequestMethod.POST)
	public String register(
			@RequestParam(value="loginname") String loginname,
			@RequestParam(value="username") String username,
			@RequestParam(value="password") String password,
			Model model) {
		logger.info("register POST 正在被调用");
		User usr = new User();
		usr.setLoginname(loginname);
		usr.setUsername(username);		
		usr.setPassword(password);
		userList.add(usr);
		
		model.addAttribute("user", usr);
		return "loginForm";
	}
	
	@RequestMapping(value="/login")
	public String login(
			@RequestParam(value="loginname") String loginname,
			@RequestParam(value="password") String password,
			@RequestHeader("User-Agent") String userAgent,
			@RequestHeader(value="Accept") String [] accepts,
			Model model) {
		logger.info("login 正在被调用");
		for(User usr:userList) {
			if(usr.getLoginname().equals(loginname) 
					&& usr.getPassword().equals(password)) {
				model.addAttribute("username", usr.getUsername());
				return "welcome";
			}
		}
		return "registerForm";
	}
}
